<template>
  <div class="tablePageWarp">
    <div>
      <a-form layout="vertical" >
        <a-row :gutter="[16,0]">
          <!-- ECUID -->
          <a-col :md="4" :sm="24">
            <a-form-model-item :label="$t('partNumber')">
              <ecu-id-select
                v-model="queryParam.ecuModuleId"
                @change="refreshData(true)"
              ></ecu-id-select>
            </a-form-model-item>
          </a-col>
          <!--ECU名称  -->
          <a-col :md="4" :sm="24">
            <a-form-model-item :label="$t('partName')">
              <ecu-name-select
                v-model="queryParam.ecuName"
                @change="refreshData(true)"
              ></ecu-name-select>
            </a-form-model-item>
          </a-col>
          <!--软件编码-->
          <a-col :md="4" :sm="24">
            <a-form-model-item :label="$t('softwareCoding')">
              <a-select
                v-model="queryParam.softwareCode"
                @change="refreshData(true)"
                showSearch
                allow-clear
                optionFilterProp="children"
                :filterOption="false"
                @search="loadSoftWareCodes"
                :placeholder="$t('pleaseSelect') + $t('softwareCoding')"
                style="width: 100%"
              >
                <a-select-option
                  v-for="(item, index) in filterEcuList"
                  :key="index"
                  :value="item"
                  :title="item"
                >{{ item }}</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <!-- 更新时间-->
          <a-col :md="6" :sm="24">
            <a-form-model-item :label="$t('更新时间')">
              <a-range-picker
                @change="selectDateRange"
                v-model="createTime"
                :show-time="{
                  hideDisabledOptions: true,
                  defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('23:59:59', 'HH:mm:ss')],
                }"
                style="width: 100%"
                :placeholder="['更新时间-开始','更新时间-结束']"
              />
            </a-form-model-item>
          </a-col>
          <a-col :md="6" :sm="24" style="margin-top: 22px;">
            <div class="searchBtns">
              <a-button-group>
                <auth-button :auth="openType==='formal'?managePerms.vehicle2.ecuView:managePerms.vehicle2.testEcuView" type="primary" @click="refreshData(true)">
                  <i class="iconfont icon-chazhao"></i>
                  {{ $t('inquiry') }}
                </auth-button>
                <a-button @click="initiSelectValue">
                  <i class="iconfont icon-qingkong"></i>
                  {{ $t('clear') }}
                </a-button>
              </a-button-group>
            </div>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <div class="commonTableSty">
      <s-table
        class="h100"
        ref="table"
        :columns="columns"
        :data="loadData"
        :scrollX="900"
        rowKey="ecuModuleId"
        size="default" >
        <template slot-scope="text" v-for="column in commonColumns" :slot="column.scopedSlots.customRender">
          <table-ellipsis :text="text || '-'" :key="column.key"></table-ellipsis>
        </template>
        <template slot="ecuName" slot-scope="text, record">
          <a @click="showEcuDetail(record)">
            <table-ellipsis :text="text || '-'"></table-ellipsis>
          </a>
        </template>
        <template slot="ecuChangeOrigin" slot-scope="text, record">
          <table-ellipsis :text="$store.getters.getDictCodeObj('ecuChangeOriginDictCode')[text] || '-'"></table-ellipsis>
        </template>
        <!-- 软件编码[车端上报] -->
        <template slot="currentEcuSoftwareCode" slot-scope="text, record">
          <span v-if="text && record.softwareCode && text.toUpperCase() != record.softwareCode.toUpperCase()" style="font-weight:bold;color: red;">
            {{ record.currentEcuSoftwareCode }}
          </span>
          <question-mark-tip
            v-if="text && record.softwareCode && text.toUpperCase() != record.softwareCode.toUpperCase()"
            :tip-title="$t('与云端录入软件编码存在差异')"
            :popupContainer="getPopupContainer"
          ></question-mark-tip>
          <span v-else>{{ record.currentEcuSoftwareCode || '-' }}</span>
          <span v-if="record.currentEcuSoftwareCode==='7F22'">{{ '(消极应答)' }}</span>
        </template>
        <!-- 软件版本 -->
        <template slot="currentVersion" slot-scope="text, record">
          <span>{{ text || '-' }}{{ text==='7F22'?'(消极应答)':'' }}</span>
        </template>
        <!-- 硬件版本 -->
        <template slot="hardVersion" slot-scope="text, record">
          <span>{{ text || '-' }}{{ text==='7F22'?'(消极应答)':'' }}</span>
        </template>
        <template slot="action" slot-scope="text, record">
          <span style="display: flex;">
            <auth-button
              :auth="openType==='formal'?managePerms.vehicle2.versionSynchronizationHistory:managePerms.vehicle2.testVersionSynchronizationHistory"
              type="primary"
              :ghost="true"
              size="small"
              style="margin-right: 12px;"
              @click="showVersionSyncHistory(record)"
            >{{ $t('版本同步历史') }}</auth-button>
            <auth-button
              :auth="openType==='formal'?managePerms.vehicle2.upgradeHistory:managePerms.vehicle2.testUpgradeHistory"
              type="primary"
              :ghost="true"
              size="small"
              @click="showUpgradeHistory(record)"
            >{{ $t('升级历史') }}</auth-button>
          </span>
        </template>
      </s-table>
    </div>
    <!-- ECU详情 -->
    <custom-modal
      :width="1100"
      :visible="ecuDetailVisible"
      title="ECU详情"
      :destroyOnClose="true"
      class="largeVersionPopup"
      @cancel="handleCancelEcuDetail"
      modalCls=".largeVersionPopup"
      :isOkBtn="false"
      :bodyStyle="{ height: '500px', overflowY: 'auto' }">
      <ecu-detail :ecuModuleId="ecuModuleId" :id="primaryKeyId"></ecu-detail>
    </custom-modal>
    <!-- 版本同步历史 -->
    <custom-modal
      :width="1100"
      :visible="syncVisible"
      :title="versionSyncHistoryTitle"
      :destroyOnClose="true"
      class="largeVersionPopup"
      @cancel="handleCancelVersionSyncHistory"
      modalCls=".largeVersionPopup"
      :isOkBtn="false"
      :bodyStyle="{ height: '500px', overflowY: 'auto' }">
      <version-sync-history :vin="vin" :ecuId="ecuId"></version-sync-history>
    </custom-modal>
    <!-- 升级历史 -->
    <a-modal
      :width="1100"
      :visible="upgradeHistoryVisible"
      :destroyOnClose="true"
      title="升级历史"
      :bodyStyle="{ height: '500px'}"
      @cancel="handleCancelUpgradeHistory">
      <ecu-upgrade-history :ecuId="ecuId" :vin="vin"></ecu-upgrade-history>
      <template #footer>
        <slot name="footer">
          <a-button cancel @click="handleCancelUpgradeHistory">{{ $t('cancel') }}</a-button>
        </slot>
      </template>
    </a-modal>
  </div>
</template>
<script>
import TableEllipsis from '@/components/Ellipsis/TableEllipsis'
import { STable } from '@/components'
import IsStandardConfigIcon from './IsStandardConfigIcon'
import AuthText from '@/components/AuthText'
import { statisticsPerms } from '@/config/permission/index'
import moment from 'moment'
import AuthButton from '@/components/AuthButton'
import CustomModal from '@/components/CustomModal/index.vue'
import EcuDetail from '@/views/system/ecu/components/EcuDetail.vue'
import { archivesVehicleEcuColumns } from '@/views/vehicle/config/list'
import { EcuVersionDetailCols } from '@/views/task/test/list'
import VersionSyncHistory from '@/views/vehicle/components/VersionSyncHistory.vue'
import EcuUpgradeHistory from '@/views/vehicle/components/EcuUpgradeHistory.vue'
import EcuNameSelect from '@/views/components/EcuNameSelect.vue'
import EcuIdSelect from '@/views/components/EcuIdSelect.vue'
import {managePerms} from '@/config/permission/index'
import QuestionMarkTip from '@/views/components/QuestionMarkTip'
const initQueryParam = {
  ecuModuleId: undefined,
  ecuName: undefined,
  softwareCode: undefined
}
export default {
  components: {
    TableEllipsis,
    STable,
    IsStandardConfigIcon,
    AuthText,
    AuthButton,
    CustomModal,
    EcuDetail,
    VersionSyncHistory,
    EcuUpgradeHistory,
    EcuNameSelect,
    EcuIdSelect,
    QuestionMarkTip
  },
  watch: {
    activeKey: {
      handler (val) {
        if (val === 'vehiclePart') {
          this.refreshData()
          this.resize()
        }
      }
    }
  },
  props: {
    compt:{
      type: String,
      default: ''
    },
    vehicleId: {
      type: String,
      default: ''
    },
    activeKey: {
      type: String,
      default: ''
    },
    openType: {
      type: String,
      default: ''
    }
  },
  computed: {
    commonColumns () {
      return this.columns.filter(item => !item.special)
    }
  },
  created () {
    this.loadSoftWareCodes('')
    this.$store.dispatch('getEcuChangeOriginDictCodeData')
  },
  data () {
    return {
      managePerms,
      moment,
      columns: this.compt == "newLoopUse"?[...EcuVersionDetailCols]:[...archivesVehicleEcuColumns],
      // 列表数据
      tableData: [],
      statisticsPerms,
      queryParam: { ...initQueryParam },
      // 软件编码下拉框数据
      filterEcuList: [],
      createTime: null,
      // ECU详情
      ecuDetailVisible: false,
      // 打开ECU详情弹窗用的ID
      ecuModuleId: '',
      // 版本同步历史
      syncVisible: false,
      // 升级历史
      upgradeHistoryVisible: false,
      vin: '',
      ecuId: '',
      primaryKeyId: '',
      versionSyncHistoryTitle: ''
    }
  },
  methods: {
    resize () {
      this.$refs.table.getDomHeight()
    },
    getPopupContainer () {
      return document.body
    },
    // 打开ECU升级历史
    showUpgradeHistory (record) {
      this.upgradeHistoryVisible = true
      this.vin = record.vin
      this.ecuId = record.ecuModuleId
    },
    // 关闭ECU升级历史
    handleCancelUpgradeHistory () {
      this.upgradeHistoryVisible = false
    },
    // 打开版本历史同步
    showVersionSyncHistory (record) {
      this.versionSyncHistoryTitle = record.ecuName
      this.syncVisible = true
      this.vin = record.vin
      this.ecuId = record.ecuModuleId
    },
    // 关闭历史同步
    handleCancelVersionSyncHistory () {
      this.syncVisible = false
    },
    // 关闭ECU详情弹窗
    handleCancelEcuDetail () {
      this.ecuDetailVisible = false
    },
    // 打开ECU详情弹窗
    showEcuDetail (record) {
      this.ecuDetailVisible = true
      this.ecuModuleId = record.ecuModuleId
      this.primaryKeyId = record.ecuId
    },
    // 下拉框 重置和初始化
    initiSelectValue () {
      this.queryParam = { ...initQueryParam }
      this.createTime = undefined
      this.refreshData(true)
    },
    // 刷新
    refreshData (isToFirstPage = false) {
      const vm = this
      vm.$nextTick(() => {
        this.$refs.table.refresh(isToFirstPage)
      })
    },
    loadData (parameter) {
      const vm = this
      // 如果是全部则不传值给后端
      const JnqueryParam = JSON.parse(JSON.stringify(vm.queryParam))
      // eslint-disable-next-line no-restricted-syntax
      for (const key in JnqueryParam) {
        if (JnqueryParam[key] === '') {
          JnqueryParam[key] = undefined
        }
      }
      this.tableData = []
      const apiPromise = vm.$api.getVehiclePartData({ ...parameter, ...JnqueryParam, vehicleId: this.vehicleId })
      return new Promise((resolve, reject) => {
        return apiPromise.then(res => {
          if (res.data) {
            this.tableData = res.data
          }
          resolve(res)
        }).catch(err => {
          reject(err)
        })
      })
    },
    // 上报时间选择
    selectDateRange (date, dateString) {
      this.queryParam.createTimeStart = dateString[0]
      this.queryParam.createTimeEnd = dateString[1]
      this.refreshData(true);
    },
    // 软件编码下拉数据
    loadSoftWareCodes (val) {
      this.$api.getEcuList({ softwareCode: val, pageSize: 100 }).then(res => {
        // 软件编码去重
        this.filterEcuList = new Set([...res.data].map(ecu => ecu.softwareCode))
      })
    }
  }
}
</script>
<style scoped lang="less">
 ::v-deep .ant-form-item-label {
  padding-bottom: 2px;
}
::v-deep .ant-form-item {
  margin-bottom: 0;
}
.largeVersionPopup {}
</style>
